package com.vanke.kotlin_mvp

import android.content.Intent
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.view.*
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.PopupMenu
import android.widget.TextView
import com.vanke.kotlin_mvp.addedit.AddEditTaskActivity
import com.vanke.kotlin_mvp.data.Task
import com.vanke.kotlin_mvp.main.TasksFilterType
import com.vanke.kotlin_mvp.taskdetail.TaskDetailActivity
import kotlinx.android.synthetic.main.main_fragment.*
import kotlinx.android.synthetic.main.main_fragment.view.*


/**
 * @name Kotlin_MVP
 * @package name：com.vanke.kotlin_mvp
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/16 11:25
 */
class MainFragment : Fragment(), MainContract.View {
    override fun showCompletedFilterLabel() {
        filteringLabel.text = "Completed To-Do"
    }

    companion object {
        fun newInstance(): MainFragment {
            return MainFragment()
        }
    }

    internal var itemListener: TaskItemListener = object : TaskItemListener {
        override fun onTaskClick(task: Task) {
            presenter?.OpenTaskDetails(task)
        }

        override fun onCompleteTaskClick(completedTask: Task) {
            presenter?.completeTask(completedTask)
        }

        override fun onActivateTaskClick(activatedTask: Task) {
            presenter?.activateTask(activatedTask)
        }

    }

    private val listAdapter = TasksAdapter(ArrayList<Task>(), itemListener = itemListener)

    override var presenter: MainContract.Presenter? = null

    override var isActive: Boolean = false
        get() = isAdded

    override fun onResume() {
        super.onResume()
        presenter?.start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        presenter?.result(requestCode, resultCode)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.main_fragment, container, false)

        with(root) {
            val listView = main_list.apply {
                adapter = listAdapter
            }
            refresh_layout.apply {
                setColorSchemeColors(
                        ContextCompat.getColor(activity, R.color.colorPrimary),
                        ContextCompat.getColor(activity, R.color.colorAccent),
                        ContextCompat.getColor(activity, R.color.colorPrimaryDark)
                )
                scrollUpChild = listView
                setOnRefreshListener { presenter?.loadTasks(false) }
            }

            empty_hint.setOnClickListener { showAddTask() }
        }

        activity.findViewById<FloatingActionButton>(R.id.fad_add_task).apply {
            setImageResource(R.drawable.ic_add)
            setOnClickListener { presenter?.addNewTask() }
        }
        setHasOptionsMenu(true)

        return root
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_clear -> presenter?.clearCompletedTasks()
            R.id.menu_filter -> showFilteringPopUpMenu()
            R.id.menu_refresh -> presenter?.loadTasks(true)
        }
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) {
        inflater.inflate(R.menu.tasks_fragment_menu, menu)
    }

    override fun showFilteringPopUpMenu() {
        PopupMenu(context, activity.findViewById(R.id.menu_filter)).apply {
            menuInflater.inflate(R.menu.filter_tasks, menu)
            setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.active -> presenter?.currentFiltering = TasksFilterType.ACTIVE_TASKS
                    R.id.completed -> presenter?.currentFiltering = TasksFilterType.COMPLETED_TASKS
                    else -> presenter?.currentFiltering = TasksFilterType.ALL_TASKS
                }
                presenter?.loadTasks(false)
                true
            }
            show()
        }
    }

    override fun setLoadingIndicator(active: Boolean) {
        val root = view ?: return
        with(refresh_layout) {
            post { isRefreshing = active }
        }
    }

    override fun showTasks(tasks: List<Task>) {
        listAdapter.tasks = tasks
        main_ll.visibility = View.VISIBLE
        empty_view.visibility = View.GONE
    }

    override fun showAddTask() {
        val intent = Intent(context, AddEditTaskActivity::class.java)
        startActivityForResult(intent,AddEditTaskActivity.REQUEST_ADD_TASK)

    }

    override fun showTaskDetailsUi(taskId: String) {
        val intent = Intent(context, TaskDetailActivity::class.java).apply {
            putExtra(TaskDetailActivity.EXTRA_TASK_ID,taskId)
        }

        startActivity(intent)
    }

    override fun showTaskMarkedComplete() {
        showMessage("Task marked complete")
    }

    private fun showMessage(msg: String) {
        view?.let {
            Snackbar.make(it, msg, Snackbar.LENGTH_LONG).show()
        }
    }

    override fun showTaskMarkedActive() {
        showMessage("Task marked active")
    }

    override fun showCompletedTasksCleared() {
        showMessage("Completed tasks cleared")
    }

    override fun showLoadingTasksError() {
        showMessage("Error while loading tasks")
    }

    override fun showNoTasks() {
        shownNotaskViews("You have no To-Do", R.drawable.ic_check_circle_24dp, false)
    }

    override fun showActiveFilterLable() {
        filteringLabel.text = "Active To-Do"
    }

    override fun showAllFilterLable() {
        filteringLabel.text = "All To-Do"
    }

    override fun showNoActiveTasks() {
        shownNotaskViews("You have no active To-Do", R.drawable.ic_check_circle_24dp, false)
    }

    override fun showNoCompletedTasks() {
        shownNotaskViews("You have no completed To-Do", R.drawable.ic_verified_user_24dp, false)
    }

    private fun shownNotaskViews(text: String, icon: Int, showAddView: Boolean) {
        empty_view.visibility = View.GONE
        empty_text.text = text
        empty_icon.setImageDrawable(resources.getDrawable(icon))
        empty_hint.visibility = if (showAddView) View.VISIBLE else View.GONE
    }

    override fun showSuccessfullySavedMessage() {
        showMessage("Todo saved")
    }


    interface TaskItemListener {
        fun onTaskClick(task: Task)

        fun onCompleteTaskClick(completedTask: Task)

        fun onActivateTaskClick(activatedTask: Task)
    }

    private class TasksAdapter(tasks: List<Task>, private val itemListener: TaskItemListener)
        : BaseAdapter() {

        var tasks: List<Task> = tasks
            set(tasks) {
                field = tasks
                notifyDataSetChanged()
            }

        override fun getView(p0: Int, p1: View?, p2: ViewGroup): View {
            val rowView = p1 ?: LayoutInflater.from(p2.context).inflate(R.layout.task_item, p2, false)

            val task = getItem(p0)

            with(rowView.findViewById<TextView>(R.id.title)) {
                text = task.titleForList
            }

            with(rowView.findViewById<CheckBox>(R.id.complete)) {
                isChecked = task.isCompleted
                rowView.setBackgroundDrawable(p2.context.resources.getDrawable(
                        if (task.isCompleted) R.drawable.list_completed_touch_feedback else R.drawable.touch_feedback
                ))
                setOnClickListener {
                    if (!task.isCompleted) {
                        itemListener.onCompleteTaskClick(task)
                    } else {
                        itemListener.onActivateTaskClick(task)
                    }
                }
            }

            rowView.setOnClickListener { itemListener.onTaskClick(task) }

            return rowView

        }

        override fun getItem(p0: Int): Task {
            return tasks[p0]
        }

        override fun getItemId(p0: Int): Long {
            return p0.toLong()
        }

        override fun getCount(): Int {
            return tasks.size
        }

    }
}